<?php

/**
 * User: Lomon
 * Date: 2020/12/10
 *
 */
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\Db;

class SendTravelMsg extends Command
{
    protected function configure()
    {
        $this->setName('SendTravelMsg')->setDescription('发送旅游路线消息通知');
    }
    protected function execute(Input $input, Output $output)
    {
        $output->writeln(date('Y-m-d H:i:s'));
        $output->writeln('start:'.$this->getName());
        /*** 这里写计划任务列表集 START ***/

        //----------------是否在运行--------------//
        $uname = php_uname();
        if(strpos(strtolower($uname),'linux') !== false) {
            $maxnum = 1;//最大线程数
           $n = exec("ps aux |grep '" . $this->getName() . "' | grep -v grep | wc -l");
            if ($n > $maxnum) {
                die(date("Y-m-d H:i:s") . $this->getName() . " is running");
            }
        }

        // TODO 获取所有路线小礼包,状态是即将报名的,并且是还没有发送过消息的
        $giftList = db('retail_gift_give')
            ->field('*')
            ->where('type','travel')
            ->where('status','up')
            ->where('salestatus','2')
            ->where('is_send_msg','0')
            ->select();
        $giftList = \collection($giftList)->toArray();

        if(!empty($giftList)){
            // TODO 有权限领取旅游小礼包的所有用户
            $userGift = db('retail_userbuy_gift')
                ->field('user_id')
                ->where('type','travel')
                ->select();

            $userGift = \collection($userGift)->toArray();
            foreach ($userGift as $item){
                $userIds[] = $item['user_id'];
            }
            foreach ($giftList as $item){
                //按每个路线和每个用户发送提醒消息
                $res = $this->sendMsgToUser($userIds,$item);

                /**更新礼包发送消息的情况 */
                db('retail_gift_give')->where(['id'=>$item['id'],'type'=>$item['type']])->update(['is_send_msg'=>'1']);
            }


        }

    }

    /**
     * 给用户发消息
     * @param $userIds 所有用户ID
     * @param $gift 路线小礼包信息
     */
    protected function sendMsgToUser($userIds,$gift)
    {
        $userModel = new \addons\shopro\model\User();
        foreach ($userIds as $user_id){
            $model = clone $userModel;
            $user = $model->find($user_id);

            if(empty($user)){ continue;}
            $travel_info = [
                'travel_id'=>$gift['id'],
                'title'=>$gift['title'],
                'remark'=>'旅游路线即将开始报名',
                'start_time'=>date('Y-m-d H:i',$gift['starttime']),
            ];

            $user->notify(
                new \addons\shopro\notifications\Travel([
                    'travel_info' => $travel_info,
                    'event' => 'travel_start'
                ])
            );
            sleep(1);
        }
        return true;
    }
}